package com.cyw.common.config.jackson.deserializer;

import com.cyw.common.utils.DateUtils;
import com.cyw.common.utils.RegexUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.time.LocalDate;

/**
 * LocalDate反序列化
 *
 * @author cyw
 * @date 2021-03-31
 */
public class StringOrTimestamp2LocalDateDeserializer extends StdDeserializer<LocalDate> {

    private static final long serialVersionUID = 4309867928567488571L;

    public StringOrTimestamp2LocalDateDeserializer() {
        this(null);
    }

    public StringOrTimestamp2LocalDateDeserializer(Class<LocalDate> vc) {
        super(vc);
    }

    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext context) throws IOException {
        String time = StringUtils.trim(p.getText());

        return RegexUtils.isTimeStampMilli(time) ?
                DateUtils.timestamp2LocalDate(p.getValueAsLong()) :
                DateUtils.parseLocalDate(time);
    }
}